import { isEmpty, get } from 'lodash-es';
import { defineStore } from 'pinia';
import { USER_SIDE_MENUS_KEY } from '../config/index.js';
import { handleCommonRes } from '../utils/resolver';
import { flattenDeep, replaceFields } from '../utils/index.js';
import { getKeyMenuDataEnum, getMenuDataGetter } from './menu.js';
import vueGlobal from '../vueGlobal.js';
import storage from '../utils/storage.js';
import { getStoreId } from './utils.js';

const id = getStoreId('SideMenuStore');
export const useSideMenuStore = defineStore(id, {
  state: () => ({
    menus: [],
    keyMenuEnum: {},
    permissions: [],
    menuFieldsMap: {
      childrenKey: 'nodes',
      permissionKey: 'url',
      titleKey: 'name',
      iconKey: 'img_url',
      key: 'id',
    },
  }),
  getters: {
    getMenuData(state) {
      return function () {
        return getMenuDataGetter.apply(state.keyMenuEnum, arguments);
      };
    },
    isPathHasPermission: (state) => (to) => {
      let permission = get(to, 'meta.permission');
      if (permission === undefined || permission === true) {
        return true;
      }
      if (!state.permissions || !state.permissions.length) {
        return false;
      }
      if (!Array.isArray(permission)) {
        permission = [permission];
      }
      return permission.some((item) => state.permissions.indexOf(item) >= 0);
    },
  },
  actions: {
    clearSideMenu() {
      this.$reset();
    },
    async getMenuAsync(fieldsMap) {
      fieldsMap = Object.assign({}, fieldsMap);
      if (!isEmpty(this.menus)) {
        return;
      }
      const { childrenKey, permissionKey, titleKey, iconKey, key } = this.menuFieldsMap;
      let data = storage.session.getItem(USER_SIDE_MENUS_KEY);
      if (isEmpty(data)) {
        const $axios = vueGlobal.get('$axios');
        const api = (params) => $axios.get('/xw-microservice/xw-system/v3/menu/userMenu', { params });
        data = await handleCommonRes(api, null, {
          onFail: () => {
            vueGlobal.get('$message').error('菜单获取失败，请稍后再试！');
            this.menus = [];
            this.keyMenuEnum = {};
            this.permissions = [];
          },
        });
        data = get(data, `[0].${childrenKey}`) || [];
        storage.session.setItem(USER_SIDE_MENUS_KEY, data, { expires: 1 });
      }
      // const idtPathEnum = getPermissionKeyPathEnum();
      //能进行访问的页面
      this.permissions = flattenDeep(data, {
        deep: (item) => item[childrenKey],
        filter: (val) => !!val,
        format: (item) => String(item[permissionKey]).trim(),
      });
      this.menus = replaceFields(data, {
        // key 就是路由地址
        // key: (item) => idtPathEnum[String(item[permissionKey]).trim()] || '/404',
        key: key,
        icon: iconKey,
        title: titleKey,
        path: permissionKey,
        children: childrenKey,
      });
      this.keyMenuEnum = getKeyMenuDataEnum(this.menus);
    },
  },
});
